package chinesechess.view;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import chinesechess.DTO.DBConnection;

import java.awt.*;
import java.sql.*;

public class BattleRecordFrame extends JFrame {
    
    public BattleRecordFrame(int userId) {
        // 首先获取用户昵称
        String nickname = "";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(
                     "SELECT user_nickname FROM score WHERE user_id = ?")) {
            
            pstmt.setInt(1, userId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                nickname = rs.getString("user_nickname");
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        // 设置标题包含玩家昵称
        setTitle("对战记录 - " + nickname);
        setSize(500, 400);
        setLocationRelativeTo(null);
        
        // 创建表格模型
        String[] columnNames = {"时间", "对战类型", "获得积分"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        // 从数据库获取当前用户的对战记录
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(
                     "SELECT battle_time, duizhan, score FROM laiyuan " +
                     "WHERE user_id = ? ORDER BY battle_time DESC")) {
            
            pstmt.setInt(1, userId);
            ResultSet rs = pstmt.executeQuery();
            
            while (rs.next()) {
                model.addRow(new Object[]{
                    rs.getTimestamp("battle_time"),
                    rs.getString("duizhan"),
                    "+" + rs.getInt("score")
                });
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        // 创建表格
        JTable table = new JTable(model);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.setRowHeight(30);
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        
        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        
        // 关闭按钮
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dispose());
        
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(closeButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }
} 